﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Storage;
using System.Net.Mail;

namespace TripLOA.GUI.roles
{
    public partial class UserInformation : TripLOA.GUI.internationalization.LOABasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
            if (!Page.IsPostBack)
            {
                string userName = Request.QueryString["user"];

                // If the url is incorrect            
                if (string.IsNullOrEmpty(userName))
                    Response.Redirect("ManageRolesToUsers.aspx");

                // Get information about this user
                MembershipUser usr = Membership.GetUser(userName);
                if (usr == null)
                    Response.Redirect("ManageRolesToUsers.aspx");

                lab_username.Text = usr.UserName;
                lab_mail.Text = usr.Email;

                //Controls if the user is always registered
                try
                {
                    if (!StorageManager.Instance.GetUserByUserName(userName).BookedIn)
                    {
                        string usernotregistered = this.GetLocalResourceObject("UserNotRegistered.Text").ToString();
                        lab_is_user_reg.Text = usernotregistered;
                    }
                }
                catch (Storage.Exceptions.UserNotFoundException)
                {
                    /*
                     * This happens when a user has been created in the membership provider 
                     * but not in the "profile" databases. Users like these are only "users 
                     * for testing phases" and they are not counted.
                     */
                }

                //Controls if the user is locked out
                if (usr.LastLockoutDate.Year < 2000)
                    lab_last_lock_date.Text = string.Empty;
                else
                    lab_last_lock_date.Text = usr.LastLockoutDate.ToShortDateString();
                but_unlock.Enabled = usr.IsLockedOut;

                
                BindRolesToList();
                CheckRolesForSelectedUser(usr.UserName);
            }
        }

        #region ROLES_OF_THE_USER
        /// <summary>
        /// binds roles to the grid that shows roles
        /// </summary>
        private void BindRolesToList()
        {
            // Get all of the roles 
            string[] roles = Roles.GetAllRoles();
            UsersRoleList.DataSource = roles;
            UsersRoleList.DataBind();

            //RoleList.DataSource = roles;
            //RoleList.DataBind();
        }

        /// <summary>
        /// determines which roles the selected user belongs to        
        /// </summary>
        /// <param name="userName">the selected user</param>
        protected void CheckRolesForSelectedUser(string userName)
        {            
            string[] selectedUsersRoles = Roles.GetRolesForUser(userName);

            // Loop through the Repeater's Items and check or uncheck the checkbox as needed 
            foreach (RepeaterItem ri in UsersRoleList.Items)
            {
                CheckBox RoleCheckBox = ri.FindControl("RoleCheckBox") as CheckBox;

                // See if RoleCheckBox.Text is in selectedUsersRoles
                /*Only with ASP3.5 you can use
                if (selectedUsersRoles.Contains<string>(RoleCheckBox.Text))*/

                if (Array.IndexOf<string>(selectedUsersRoles, RoleCheckBox.Text) != -1)
                    RoleCheckBox.Checked = true;
                else
                    RoleCheckBox.Checked = false;
            }
        }

        /// <summary>
        /// manages the changes of the roles' checkboxes
        /// </summary>
        protected void RoleCheckBox_CheckChanged(object sender, EventArgs e)
        {
            // Reference the CheckBox that raised this event 
            CheckBox RoleCheckBox = sender as CheckBox;

            // Get the currently selected user and role 
            string userName = Request.QueryString["user"];
            string roleName = RoleCheckBox.Text;

            // Determine if we need to add or remove the user from this role 
            if (RoleCheckBox.Checked)
            {
                // Add the user to the role 
                Roles.AddUserToRole(userName, roleName);
                // Display a status message 
                lab_status.Text = string.Format(this.GetLocalResourceObject("UserAddedRole.Text").ToString(), userName, roleName);
            }
            else
            {
                //An admin cannot accidentally delete himself from admin role
                if (roleName.Equals("Administrators") && userName.Equals(Page.User.Identity.Name))
                {
                    lab_status.Text = string.Format(this.GetLocalResourceObject("ErrorAdmin.Text").ToString());
                }
                else
                {
                    // Remove the user from the role 
                    Roles.RemoveUserFromRole(userName, roleName);
                    // Display a status message 
                    lab_status.Text = string.Format(this.GetLocalResourceObject("UserRemovedRole.Text").ToString(), userName, roleName);
                }
            }
            
            // Refresh the "by role" interface 
            CheckRolesForSelectedUser(userName);
        }
        #endregion ROLES_OF_THE_USER

        #region UNLOCK_USER

        protected void but_unlock_Click(object sender, EventArgs e)
        {
            // Unlock the user 
            string userName = Request.QueryString["user"];
            MembershipUser usr = Membership.GetUser(userName);
            usr.UnlockUser();
            but_unlock.Enabled = false;
            

            //Send mail to the user telling him he was unlocked
            try
            {
                MailMessage msg = new MailMessage();
                msg.From = new MailAddress("triploaadmin@cli.di.unipi.it", "TriploAdmin");
                msg.To.Add(new MailAddress(usr.Email, usr.UserName));
                msg.Subject = "TripLOA: You have been Unlocked!";
                msg.SubjectEncoding = System.Text.Encoding.UTF8;

                msg.Body = "Hi " + usr.UserName + ", you have been unlocked. Your account is now active.";
                msg.BodyEncoding = System.Text.Encoding.UTF8;
                msg.IsBodyHtml = true;

                SmtpClient server = new SmtpClient();
                server.Send(msg);
            }
            catch (Exception)
            {
                string errormail = this.GetLocalResourceObject("ErrorMail.Text").ToString();
                lab_status.Text = errormail;
            }

            string unlocked = this.GetLocalResourceObject("Unlocked.Text").ToString();
            lab_status.Text = unlocked;
        }

        #endregion UNLOCK_USER

    }
}
